package server

import (
	"fmt"
	"github.com/pkg/errors"
	"server5/Interface"
	"sync"
)

var ConnManager *ConnManage

type ConnManage struct {
	Connections map[uint32]Interface.IConnection
	Lock        sync.RWMutex
}

//单例
func GetConnManager() *ConnManage {
	if ConnManager == nil {
		ConnManager = &ConnManage{
			Connections: make(map[uint32]Interface.IConnection),
		}
	}
	return ConnManager
}

func (c *ConnManage) Add(conn Interface.IConnection) {
	c.Lock.Lock()
	defer c.Lock.Unlock()
	c.Connections[conn.GetConnID()] = conn

	//Debug
	fmt.Println(conn.GetConnID(), "加入到连接管理器中")
	fmt.Println("当前连接管理器中的连接有：")
	for id,co := range c.Connections {
		fmt.Println(id,co.User().UserInfo())
	}

}

func (c *ConnManage) Remove(conn Interface.IConnection) {
	c.Lock.Lock()
	defer c.Lock.Unlock()
	delete(c.Connections, conn.GetConnID())

	//Debug
	fmt.Println(conn.GetConnID(), "从连接管理器中移除")
	fmt.Println("当前连接管理器中的连接有：")
	for id,co := range c.Connections {
		fmt.Println(id,co.User().UserInfo())
	}
}

func (c *ConnManage) Get(connId uint32) (Interface.IConnection, error) {
	c.Lock.RLock()
	defer c.Lock.RUnlock()
	conn, ok := c.Connections[connId]
	if ok {
		return conn, nil
	}
	return &Connection{}, errors.New("没有此连接")
}

func (c *ConnManage) Len() int {
	return len(c.Connections)
}

func (c *ConnManage) Clear() {
	c.Lock.Lock()
	defer c.Lock.Unlock()
	for connId, conn := range c.Connections {
		conn.Stop()
		delete(c.Connections, connId)
	}
}
